<template>
	<view class="my-posts-container">
		<!-- 统计信息 -->
		<view class="stats-section">
			<view class="stat-card">
				<i class="stat-icon fas fa-file-alt"></i>
				<text class="number">{{ posts.length }}</text>
				<text class="label">动态总数</text>
			</view>
			<view class="stat-card">
				<i class="stat-icon fas fa-heart"></i>
				<text class="number">{{ totalLikes }}</text>
				<text class="label">获赞总数</text>
			</view>
			<view class="stat-card">
				<i class="stat-icon fas fa-comments"></i>
				<text class="number">{{ totalComments }}</text>
				<text class="label">评论总数</text>
			</view>
		</view>

		<!-- 动态列表 -->
		<scroll-view class="post-list" scroll-y @scrolltolower="loadMorePosts" refresher-enabled :refresher-triggered="isRefreshing" @refresherrefresh="refreshPosts">
			<view v-if="posts.length === 0 && !isLoading" class="empty-state">
				<i class="empty-icon fas fa-box-open"></i>
				<text class="empty-text">你还没有发布任何动态哦</text>
				<button class="empty-btn" @click="goToSquare">去广场看看</button>
			</view>

			<view v-for="post in posts" :key="post.id" class="post-item">
				<view class="post-main">
					<view class="post-meta">
						<text class="post-time">{{ formatTime(post.created_at || post.CreatedAt) }}</text>
					</view>
					<view class="post-content">
						<text>{{ post.content }}</text>
					</view>
				</view>
				<view class="post-footer">
					<view class="post-stats">
						<view class="stat-item">
							<i class="far fa-heart"></i>
							<text>{{ post.likes || 0 }}</text>
						</view>
						<view class="stat-item">
							<i class="far fa-comment"></i>
							<text>{{ post.comments_count || 0 }}</text>
						</view>
					</view>
					<view class="post-actions">
						<button class="action-btn delete" @tap="handleDelete(post.id)">删除</button>
					</view>
				</view>
			</view>
			
			<uni-load-more :status="loadingStatus"></uni-load-more>
		</scroll-view>
	</view>
</template>

<script>
import { getPostsByUserId, deletePost } from '@/api/post';
import { useUserStore } from '@/stores/user';
import { formatTime } from '../../utils/date-utils';
import { checkLoginStatus } from '@/utils/auth';
import uniLoadMore from '@dcloudio/uni-ui/lib/uni-load-more/uni-load-more.vue';

export default {
	components: {
		uniLoadMore
	},
	data() {
		return {
			posts: [],
			page: 1,
			hasMore: true,
			isLoading: false,
			isRefreshing: false,
			totalLikes: 0,
			totalComments: 0
		};
	},
	computed: {
		loadingStatus() {
			if (this.isLoading) return 'loading';
			if (!this.hasMore) return 'noMore';
			return 'more';
		}
	},
	onLoad() {
		if (!checkLoginStatus()) {
			uni.reLaunch({
				url: '/pages/login/login'
			});
			return;
		}
		const systemInfo = uni.getSystemInfoSync();
		this.isMobile = systemInfo.windowWidth < 768;
		this.isTablet = systemInfo.windowWidth >= 768 && systemInfo.windowWidth < 1024;
		this.isDesktop = systemInfo.windowWidth >= 1024;
		this.loadPosts(true);
	},
	methods: {
		formatTime,
		async loadPosts(reset = false) {
			if (this.isLoading) return;
			this.isLoading = true;

			if (reset) {
				this.page = 1;
				this.posts = [];
				this.hasMore = true;
			}

			try {
				const userStore = useUserStore();
const userId = userStore.userId;
				if (!userId) {
					uni.reLaunch({ url: '/pages/login/login' });
					return;
				}
				
				const response = await getPostsByUserId(userId, { page: this.page });
				
				let newPosts = [];
				if (response && Array.isArray(response)) {
					newPosts = response;
				} else if (response && Array.isArray(response.posts)) {
					newPosts = response.posts;
				}

				if (newPosts.length > 0) {
					this.posts = [...this.posts, ...newPosts];
					this.hasMore = newPosts.length > 0;
					this.page++;
					this.totalLikes = this.posts.reduce((sum, post) => sum + (post.likes || 0), 0);
					this.totalComments = this.posts.reduce((sum, post) => sum + (post.comments_count || 0), 0);
				} else {
					this.hasMore = false;
				}
			} catch (error) {
				console.error("获取用户动态失败:", error);
				uni.showToast({ title: '加载动态失败', icon: 'none' });
			} finally {
				this.isLoading = false;
				this.isRefreshing = false;
			}
		},
		async refreshPosts() {
			this.isRefreshing = true;
			await this.loadPosts(true);
		},
		loadMorePosts() {
			if (this.hasMore && !this.isLoading) {
				this.loadPosts();
			}
		},
		async handleDelete(postId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这条动态吗？此操作无法撤销。',
				success: async (res) => {
					if (res.confirm) {
						try {
							await deletePost(postId);
							uni.showToast({ title: '删除成功', icon: 'success' });
							this.posts = this.posts.filter(p => p.id !== postId);
							this.totalLikes = this.posts.reduce((sum, post) => sum + (post.likes || 0), 0);
							this.totalComments = this.posts.reduce((sum, post) => sum + (post.comments_count || 0), 0);
						} catch (error) {
							console.error("删除动态失败:", error);
							uni.showToast({ title: '删除失败', icon: 'none' });
						}
					}
				}
			});
		},
		goToSquare() {
			uni.switchTab({
				url: '/pages/square/square'
			});
		}
	}
}
</script>

<style scoped src="./my-posts.css"></style>